import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import crypto from 'crypto';
import { AdminAuthService } from '@/services/AdminAuthService';

// 生成会话令牌
function generateSessionToken() {
  return crypto.randomBytes(32).toString('hex');
}

// 验证会话令牌
function verifySessionToken(token: string) {
  // 在实际应用中，应该将会话令牌存储在数据库或Redis中
  // 这里简化处理，仅从cookie中获取并验证
  const storedToken = cookies().get('admin_session')?.value;
  return storedToken === token;
}

// 登录验证
export async function POST(request: NextRequest) {
  try {
    const { password } = await request.json();
    const authService = new AdminAuthService();

    if (!(await authService.hasPasswordSet())) {
      // 如果还没有设置密码，使用第一个提供的密码作为初始密码
      await authService.setPassword(password);
      const sessionToken = generateSessionToken();
      cookies().set('admin_session', sessionToken, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        maxAge: 60 * 60 * 24, // 24小时有效期
      });
      return NextResponse.json({
        success: true,
        message: '初始密码设置成功，已自动登录',
      });
    }

    if (await authService.verifyPassword(password)) {
      const sessionToken = generateSessionToken();
      cookies().set('admin_session', sessionToken, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        maxAge: 60 * 60 * 24, // 24小时有效期
      });
      return NextResponse.json({
        success: true,
        message: '登录成功',
      });
    } else {
      return NextResponse.json(
        {
          success: false,
          message: '密码错误',
        },
        {
          status: 401,
        }
      );
    }
  } catch (error) {
    console.error('登录失败:', error);
    return NextResponse.json(
      {
        success: false,
        message: '服务器错误',
      },
      {
        status: 500,
      }
    );
  }
}

// 更改密码
export async function PUT(request: NextRequest) {
  try {
    // 验证会话
    const sessionToken = request.headers.get('Authorization')?.replace('Bearer ', '');
    if (!sessionToken || !verifySessionToken(sessionToken)) {
      return NextResponse.json(
        {
          success: false,
          message: '未授权访问',
        },
        {
          status: 401,
        }
      );
    }

    const { oldPassword, newPassword } = await request.json();
    const authService = new AdminAuthService();

    if (await authService.changePassword(oldPassword, newPassword)) {
      return NextResponse.json({
        success: true,
        message: '密码更改成功',
      });
    } else {
      return NextResponse.json(
        {
          success: false,
          message: '旧密码错误',
        },
        {
          status: 401,
        }
      );
    }
  } catch (error) {
    console.error('更改密码失败:', error);
    return NextResponse.json(
      {
        success: false,
        message: '服务器错误',
      },
      {
        status: 500,
      }
    );
  }
}

// 登出
export async function DELETE(request: NextRequest) {
  try {
    cookies().delete('admin_session');
    return NextResponse.json({
      success: true,
      message: '登出成功',
    });
  } catch (error) {
    console.error('登出失败:', error);
    return NextResponse.json(
      {
        success: false,
        message: '服务器错误',
      },
      {
        status: 500,
      }
    );
  }
}

// 检查登录状态
export async function GET(request: NextRequest) {
  try {
    const sessionToken = request.headers.get('Authorization')?.replace('Bearer ', '');
    if (sessionToken && verifySessionToken(sessionToken)) {
      return NextResponse.json({
        success: true,
        isLoggedIn: true,
      });
    } else {
      return NextResponse.json({
        success: true,
        isLoggedIn: false,
      });
    }
  } catch (error) {
    console.error('检查登录状态失败:', error);
    return NextResponse.json(
      {
        success: false,
        message: '服务器错误',
      },
      {
        status: 500,
      }
    );
  }
}